import React from 'react';
import './index.less';
import { Form, Input, Button } from 'antd';
import {connect} from 'react-redux';
import {register} from '../../../redux/action/actions';

const CRegisterForm = (props) => {
  const [form] = Form.useForm();

  const formItemLayout = {
    labelCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 8,
      },
    },
    wrapperCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 16,
      },
    },
  };

  const tailFormItemLayout = {
    wrapperCol: {
      xs: {
        span: 24,
        offset: 0,
      },
      sm: {
        span: 16,
        offset: 10,
      },
    },
  };

  const onFinish = async (values) => {
    props.register(values);
    props.registerCancel();
  };


  return (
    <Form
    {...formItemLayout}
    form={form}
    name="register"
    onFinish={onFinish}
    scrollToFirstError
    >
      <Form.Item
        name="username"
        label="username"
        getValueFromEvent={(e)=>{ // 输入值里不允许有空格
          return e.target.value.replace(/(^\s*)|(\s*$)/g, '');
        }}
        rules={[
          {
            required: true,
            message: 'Please input your username!',
            whitespace: true,
          },
        ]}
      >
        <Input maxLength={12} autoComplete="off" />
      </Form.Item>

      <Form.Item
        name="password"
        label="password"
        getValueFromEvent={(e)=>{ // 输入值里不允许有空格
          return e.target.value.replace(/(^\s*)|(\s*$)/g, '');
        }}
        rules={[
          {
            required: true,
            message: 'Please input your password!',
          },
        ]}
        hasFeedback
      >
        <Input.Password maxLength={20} />
      </Form.Item>

      <Form.Item
        name="confirm"
        label=" confirm password"
        dependencies={['password']}
        hasFeedback
        rules={[
          {
            required: true,
            message: 'Please confirm your password!',
          },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('password') === value) {
                return Promise.resolve();
              }

              return Promise.reject(new Error('The two passwords that you entered do not match!'));
            },
          }),
        ]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item {...tailFormItemLayout} style={{marginTop: '30px'}} >
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  )
}

export default connect(
  state => state,
  {register}
)(CRegisterForm);